package com.fafu.mq.mqserver.core;

import com.fafu.mq.common.ConsumerEnv;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 表示一个存储消息的队列
 */

@Data
public class MSGQueue {
    //唯一标识
    private String name;
    //是否持久化
    private boolean durable;
    //这个队列只能被一个消费者使用当为 true 的时候, 为 false 大家都可以使用
    //具体独占功能不实现
    private boolean exclusive;

    private boolean autoDelete = false;
    private Map<String, Object> arguments = new HashMap<>();
    // 当前队列都有哪些消费者订阅
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();

    private AtomicInteger consumerSeq = new AtomicInteger(0);
    // 添加一个订阅者
    public void addConsumerEnv(ConsumerEnv consumerEnv){
            consumerEnvList.add(consumerEnv);
    }
    // 挑选一个订阅者用来处理当前的消息 (采用轮询的方式)
    public ConsumerEnv chooseConsumer(){
        if (consumerEnvList.size() == 0){
            // 该队列无人订阅
            return null;
        }
        // 计算一下要取元素的下标
        int index = consumerSeq.get() % consumerEnvList.size();
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }
    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<Map<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    public Object getArguments(String key) {
        return arguments.get(key);
    }
    //这个方法, 是从数据库读数据之后, 构造 Exchange 对象会使用到
    public void setArguments(String key, Object value) {
        arguments.put(key,value);
    }
    public void setArguments(Map<String,Object> arguments) {
        this.arguments = arguments;
    }
}
